package priv.pfz.basedao.mybatis.mapper;

import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import priv.pfz.basedao.mybatis.sqlprovider.CountSqlProvider;
import priv.pfz.basedao.mybatis.sqlprovider.DeleteSqlProvider;
import priv.pfz.basedao.mybatis.sqlprovider.ListSqlProvider;
import priv.pfz.basedao.mybatis.sqlprovider.UpdateSqlProvider;
import priv.pfz.basedao.pagequery.Page;
import priv.pfz.basedao.query.BaseQuery;

import javax.annotation.Nonnull;
import java.util.List;

/**
 * 默认的BaseMapper，增加对Query类的依赖，可满足基本需求
 * @author yyjxp
 * 2024/1/28 23:09
 */
public interface DefaultBaseMapper<Entity, Query extends BaseQuery<Query>> extends SimpleBaseMapper<Entity> {
    /**
     * 按query条件批量更新多条记录
     * entity中为空的字段不会更新
     * UPDATE table SET a=entity.a, b=entity.b WHERE query
     */
    @UpdateProvider(UpdateSqlProvider.class)
    @Options(useCache = false)
    int update(@Nonnull Entity entity, @Nonnull Query query);

    /**
     * 按query条件查询数量
     * query中为空的字段不会作为查询条件
     * SELECT count(*) FROM table WHERE query
     */
    @SelectProvider(CountSqlProvider.class)
    @Options(useCache = false)
    int count(@Nonnull Query query);

    /**
     * 按query条件查询多条记录
     * query中为空的字段不会作为查询条件
     * SELECT a,b,c FROM table WHERE/ORDER_BY/LIMIT query
     */
    @SelectProvider(ListSqlProvider.class)
    @Options(useCache = false)
    List<Entity> list(@Nonnull Query query);

    /**
     * 按query中的条件删除多条记录
     * query中为空的字段不会作为删除条件
     * DELETE FROM table WHERE query
     */
    @SelectProvider(DeleteSqlProvider.class)
    @Options(useCache = false)
    int delete(@Nonnull Query query);

    /**
     * 分页查询，先调用count再调用list方法
     */
    default Page<Entity> pageQuery(@Nonnull Query query) {
        int count = count(query);
        List<Entity> entities = list(query);
        int totalPage = (int) Math.ceil((double) count / query.getPageSize());
        return new Page<>(query.getPageNo(), query.getPageSize(), count, totalPage, entities);
    }
}
